<template>
    <view class="container p-bottom">
        <view class="flow-list">
            <view v-if="goods_list.length">
                <view class="cart-edit-wrap dis-flex flex-x-end">
                    <text v-if="action === 'complete'" @tap.stop.prevent="switchAction" class="f-30" data-action="edit">编辑</text>
                    <text v-if="action === 'edit'" @tap.stop.prevent="switchAction" class="f-30" data-action="complete">完成</text>
                </view>
                <view v-for="(item, index) in goods_list" :key="index">
                    <view class="dish-item dis-flex flex-y-center" :data-index="index" :style="item.txtStyle">
                        <!-- 选择框 -->
                        <view class="dish-item-radio" @tap="radioChecked" :data-index="index">
                            <label class="radio">
                                <radio :checked="item.checked" color="#ff495e"></radio>
                            </label>
                        </view>
                        <view class="dish-item-wrp dis-flex flex-box">
                            <!-- 商品图片 -->
                            <navigator hover-class="none" :url="'../goods/index?item_id=' + item.goods_id">
                                <view @tap="flowDetail" class="dish-item-pic">
                                    <image mode="aspectFill" class="image" :src="item.image[0].file_path"></image>
                                </view>
                            </navigator>
                            <!-- 商品信息 -->
                            <view class="dish-item-info flex-box">
                                <navigator hover-class="none" :url="'../goods/index?item_id=' + item.goods_id">
                                    <view class="goods-name">
                                        <text @tap="flowDetail" class="twolist-hidden f-30 col-3">{{ item.goods_name }}</text>
                                    </view>
                                    <view class="goods-attr dis-flex">
                                        <text class="col-7 f-24">{{ item.goods_sku.goods_attr }}</text>
                                    </view>
                                </navigator>
                                <view class="dis-flex flex-x-between m-top20">
                                    <!-- 商品价格 -->
                                    <view class="wx-goods_price dis-flex flex-y-center">
                                        <text class="dish-item-money">￥{{ item.goods_price }}</text>
                                    </view>
                                    <!-- 数量选择器 -->
                                    <view class="selectNumber">
                                        <button
                                            @tap="minusCount"
                                            :class="'default ' + (item.total_num > 1 ? '' : ' default-active')"
                                            :data-index="index"
                                            :data-sku-id="item.goods_sku.key"
                                            type="default"
                                        >
                                            -
                                        </button>
                                        <input @input="importFun" :disabled="true" type="number" :value="item.total_num" />
                                        <button @tap="addCount" class="default" :data-index="index" :data-sku-id="item.goods_sku.key" type="default">+</button>
                                    </view>
                                </view>
                                <!-- 删除按钮 -->
                                <!-- <view catchtap="del" class="flow-dete" data-goods-id="{{item.goods_id}}" data-sku-id="{{item.goods_sku.key}}">
                <text class="iconfont icon-lajixiang"></text>
              </view> -->
                            </view>
                        </view>
                    </view>
                </view>
                <!-- 底部操作栏 -->
                <view class="cart-tab-wrp">
                    <view class="cart-item-total cart-tab-item dis-flex flex-y-center">
                        <view class="checked-all">
                            <label @tap.stop.prevent="radioCheckedAll" class="radio dis-flex flex-y-center">
                                <radio class="margin-right: 10rpx;" :checked="checkedAll" color="#ff495e"></radio>
                                <text class="f-28">全选</text>
                            </label>
                        </view>
                        <view v-if="action === 'complete'" class="cart-item-total-price dis-flex">
                            <text class="f-28 col-m">合计：￥{{ cartTotalPrice }}</text>
                        </view>
                    </view>
                    <view class="cart-tab-item">
                        <view v-if="action === 'complete'" @tap="submit" class="cart-tab-item-btn">去结算</view>
                        <view v-if="action === 'edit'" @tap="deleteHandle" class="cart-tab-item-btn">删除</view>
                    </view>
                </view>
            </view>
            <view v-else>
                <view class="yoshop-notcont">
                    <text class="iconfont icon-wushuju"></text>
                    <text class="cont">亲，购物车还没有商品哦</text>
                    <view @tap="goShopping" class="flow-btn-min">去购物</view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
const app = getApp();
export default {
    data() {
        return {
            goods_list: [],

            // 商品列表
            // order_total_num: 0,
            // 商品总金额
            // order_total_price: 0,

            action: 'complete',

            checkedAll: false,

            // 商品总价格
            cartTotalPrice: '0.00',

            order_total_price: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 获取购物车列表
        this.getCartList();
    },
    methods: {
        /**
         * 获取购物车列表
         */
        getCartList: function () {
            let that = this;
            app.globalData._get('cart/lists', {}, function (result) {
                that.setData({
                    goods_list: result.data.goods_list,
                    order_total_price: result.data.order_total_price,
                    action: 'complete',
                    checkedAll: false,
                    cartTotalPrice: '0.00'
                });
            });
        },

        /**
         * 选择框选中
         */
        radioChecked: function (e) {
            let that = this;
            let index = e.currentTarget.dataset.index;
            let checked = !that.goods_list[index].checked;
            that.setData(
                {
                    ['goods_list[' + index + '].checked']: checked
                },
                function () {
                    // 更新购物车已选商品总价格
                    that.updateTotalPrice();
                }
            );
        },

        /**
         * 选择框全选
         */
        radioCheckedAll: function (e) {
            let that = this;
            let goodsList = this.goods_list;
            goodsList.forEach(function (item) {
                item.checked = !that.checkedAll;
            });
            that.setData(
                {
                    goods_list: goodsList,
                    checkedAll: !that.checkedAll
                },
                function () {
                    // 更新购物车已选商品总价格
                    that.updateTotalPrice();
                }
            );
        },

        /**
         * 切换编辑/完成
         */
        switchAction: function (e) {
            let that = this;
            that.setData({
                action: e.currentTarget.dataset.action
            });
        },

        /**
         * 删除商品
         */
        deleteHandle: function () {
            let that = this;
            let cartIds = that.getCheckedIds();
            if (!cartIds.length) {
                app.globalData.showError('您还没有选择商品');
                return false;
            }
            uni.showModal({
                title: '提示',
                content: '您确定要移除选择的商品吗?',
                success: function (e) {
                    if (e.confirm) {
                        app.globalData._post_form(
                            'cart/delete',
                            {
                                item_sku_id: cartIds
                            },
                            function (result) {
                                // 获取购物车列表
                                that.getCartList();
                            }
                        );
                    }
                }
            });
        },

        /**
         * 获取已选中的商品
         */
        getCheckedIds: function () {
            let arrIds = [];
            this.goods_list.forEach(function (item) {
                if (item.checked === true) {
                    if (item.goods_sku) {
                        arrIds.push(item.goods_id + '_' + item.goods_sku.key);
                    } else {
                        arrIds.push(item.goods_id + '_1');
                    }
                }
            });
            return arrIds;
        },

        /**
         * 更新购物车已选商品总价格
         */
        updateTotalPrice: function () {
            let that = this;
            let cartTotalPrice = 0;
            that.goods_list.forEach(function (item) {
                if (item.checked === true) {
                    cartTotalPrice = that.mathadd(cartTotalPrice, item.total_price);
                }
            });
            that.setData({
                cartTotalPrice: Number(cartTotalPrice).toFixed(2)
            });
        },

        /**
         * 递增指定的商品数量
         */
        addCount: function (e) {
            let that = this;
            let index = e.currentTarget.dataset.index;
            let goodsSkuId = e.currentTarget.dataset.skuId;
            let goods = that.goods_list[index]; // order_total_price = _this.data.order_total_price;
            // 后端同步更新
            uni.showLoading({
                title: '加载中',
                mask: true
            });
            app.globalData._post_form(
                'cart/add',
                {
                    item_id: goods.goods_id,
                    goods_num: 1,
                    item_sku_id: goodsSkuId
                },
                function () {
                    // 商品数量
                    goods.total_num++;
                    // 商品总价格
                    goods.total_price = that.mathadd(goods.total_price, goods.goods_price);
                    // console.log(goods.total_price);
                    // 更新商品信息
                    that.setData(
                        {
                            ['goods_list[' + index + ']']: goods
                        },
                        function () {
                            // 更新购物车总价格
                            that.updateTotalPrice();
                        }
                    );
                },
                null,
                function () {
                    uni.hideLoading();
                }
            );
        },

        /**
         * 递减指定的商品数量
         */
        minusCount: function (e) {
            let that = this;
            let index = e.currentTarget.dataset.index;
            let goodsSkuId = e.currentTarget.dataset.skuId;
            let goods = that.goods_list[index]; // order_total_price = _this.data.order_total_price;
            console.log(goods);
            if (goods.total_num > 1) {
                // 后端同步更新
                uni.showLoading({
                    title: '加载中',
                    mask: true
                });
                app.globalData._post_form(
                    'cart/sub',
                    {
                        item_id: goods.goods_id,
                        item_sku_id: goodsSkuId
                    },
                    function () {
                        // 商品数量
                        goods.total_num--;
                        if (goods.total_num > 0) {
                            // 商品总价格
                            goods.total_price = that.mathsub(goods.total_price, goods.goods_price);
                            // console.log(goods.total_price);
                            // 更新商品信息
                            that.setData(
                                {
                                    ['goods_list[' + index + ']']: goods
                                },
                                function () {
                                    // 更新购物车总价格
                                    that.updateTotalPrice();
                                }
                            );
                        }
                    },
                    null,
                    function () {
                        uni.hideLoading();
                    }
                );
            }
        },

        /**
         * 购物车结算
         */
        submit: function () {
            let that = this;
            let cartIds = that.getCheckedIds();
            if (!cartIds.length) {
                app.globalData.showError('您还没有选择商品');
                return false;
            }
            uni.navigateTo({
                url: '../flow/checkout?order_type=cart&cart_ids=' + cartIds
            });
        },

        /**
         * 加法
         */
        mathadd: function (arg1, arg2) {
            return (Number(arg1) + Number(arg2)).toFixed(2);
        },

        /**
         * 减法
         */
        mathsub: function (arg1, arg2) {
            return (Number(arg1) - Number(arg2)).toFixed(2);
        },

        /**
         * 去购物
         */
        goShopping: function () {
            uni.switchTab({
                url: '../index/index'
            });
        },

        flowDetail() {
            console.log('占位：函数 flowDetail 未声明');
        },

        importFun() {
            console.log('占位：函数 import 未声明');
        }
    }
};
</script>
<style>
@import './index.css';
</style>
